package net.tycmc.cty.ctyms.timejob.iems.thread;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;

import net.tycmc.bulb.common.dao.BaseDAO;
import net.tycmc.bulb.common.datasource.ProxoolDataSource;
import net.tycmc.bulb.common.util.DateUtil;
import net.tycmc.bulb.common.util.MapGetter;
import net.tycmc.bulb.common.util.StringUtil;
import net.tycmc.bulb.dbutil.global.GlobalDBVar;
import net.tycmc.cty.ctyms.timejob.common.DateControl;
import net.tycmc.cty.ctyms.timejob.common.DynamicReadConfig;
import net.tycmc.cty.ctyms.timejob.common.ExceptionDataProcess;
import net.tycmc.cty.ctyms.timejob.common.ListUtil;
import net.tycmc.cty.ctyms.timejob.common.MyConnectDSTransDAO;
import net.tycmc.cty.ctyms.timejob.iems.dao.VclRoadInfoDAO;

import com.tycmc.functions.util.NumberFormat;


public class VclRoadRunner implements Runnable {
	private static Logger log = Logger.getLogger(VclRoadRunner.class);
	private String VclIDS; 
	private String isbakTable;
	private static String proxool = "proxool.test";
	private BaseDAO baseDAO;
	private Map<String,Object> param;
	/*private static String betaproxool = "proxool.beta";
	private BaseDAO BetabaseDAO;*/
	private static Logger logdata = Logger.getLogger("roadinfoLog");
	public VclRoadRunner(String vclIDS,String st,Map<String,Object> map){
		this.VclIDS = vclIDS;
		this.isbakTable = st;
		if(null == this.baseDAO){
			this.param=map;
			this.baseDAO = new BaseDAO();
			ProxoolDataSource connGetter = new ProxoolDataSource();
			connGetter.setProxoolname(proxool);
			this.baseDAO.setConnGetter(connGetter);
			//this.BetabaseDAO= new BaseDAO();
			ProxoolDataSource betaconnGetter = new ProxoolDataSource();
			//betaconnGetter.setProxoolname(betaproxool);
			//this.BetabaseDAO.setConnGetter(betaconnGetter);
			
		}
	}
	@Override
	public void run() {
		//System.out.println("道路信息统计开始--------"+DateControl.getDateTime(0));
		//这次统计时间
		int t=0;
			try {
				t = Integer.parseInt(DynamicReadConfig.getConfigProperty("config.properties", "roadinfo"));
			} catch (ConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String thisWorkDay = DateUtil.addDay(-t);
			//sql语句集合列表
			List<String> sqlList = new ArrayList<String>();
			//获取海拔、gsp里程、工作时间、位置信息时间
			List<Map<String,Object>> pstnDatas = this.getVclPstnRoadInfo(thisWorkDay,VclIDS,param);
			//获取总发动机操作时间、基于车轮的车辆速度、信息生成时间
			List<Map<String,Object>> pgnDatas = this.getVclPgnRoadInfo(thisWorkDay,VclIDS,param);
			Map<String, List<Map<String, Object>>> pstnListMap = new ListUtil().groupBy("MsgT_Vcl_ID", pstnDatas);
			Map<String, List<Map<String, Object>>> pgnListMap = new ListUtil().groupBy("msgp_vcl_id", pgnDatas);
			//海拔
			String Altitude ="";
			//GPS里程
			String GPSMile = "";
			//工作时间
			String WorkTime ="";
			//位置信息时间
			String PstnTime = "";
			//发动机工作时间
			String EgnWorkTime = "";
			//基于车轮的车辆速度
			String Speed = "";
			//信息生成时间
			String MsgTime = "";
			//设备id
			String VehicleID = "";
			//前一个点的累计gps里程
			double PreMile = 0;
			//前一个点的位置时间
			String PrePstnTime ="";
			Map<String,Object> map = new HashMap<String, Object>();
			List<Map<String,Object>> valList = null;
			List<Map<String,Object>> resultList = new LinkedList<Map<String,Object>>();
			Map<String,Map<String,Object>> dataMap = new HashMap<String, Map<String,Object>>();
			Map<String,Object> resultMap = new HashMap<String,Object>();
			boolean isflag = true;
			//处理海拔、gsp里程、工作时间、位置信息时间
			for(Map.Entry<String, List<Map<String, Object>>> entry : pstnListMap.entrySet()){
				valList = entry.getValue();
				VehicleID = entry.getKey();
				for(int i=0;i<valList.size();i++){
					map = valList.get(i);
					if(isflag){
						if(!StringUtil.isValid(MapGetter.getString(map, "MsgT_Altitude")) || !StringUtil.isValid(MapGetter.getString(map, "MsgT_Imileage")) || !StringUtil.isValid(MapGetter.getString(map, "MsgT_tWork"))){
							continue;
						}else{
							Altitude = ExceptionDataProcess.UnityDataProcess(MapGetter.getString(map, "MsgT_Altitude"),2);
							GPSMile = ExceptionDataProcess.UnityDataProcess(MapGetter.getString(map, "MsgT_Imileage"),2);
							WorkTime = ExceptionDataProcess.UnityDataProcess(MapGetter.getString(map, "MsgT_tWork"),2);
							PstnTime = MapGetter.getString(map, "MsgT_PstnTime");
							//将第一个点作为开始点为下一个点做对比
							PreMile = MapGetter.getDouble(map, "MsgT_Imileage");
							PrePstnTime = MapGetter.getString(map, "MsgT_PstnTime");
							isflag = false;
						}
					}else{
						//当前点与前一个点进行位置时间比较，如果当前点和前一个点的位置时间差小于15分钟则不满足条件
					    long time = DateControl.getMiaoShu(PrePstnTime,MapGetter.getString(map, "MsgT_PstnTime"));
					    //当前点gps累计里程和前一个点的累计里程做差，如果为负数则不满足
					    double mile = NumberFormat.sub(MapGetter.getDouble(map, "MsgT_Imileage"),PreMile);
					    if(time>=900 && mile>=0){
					    	if(!StringUtil.isValid(MapGetter.getString(map, "MsgT_Altitude")) || !StringUtil.isValid(MapGetter.getString(map, "MsgT_Imileage")) || !StringUtil.isValid(MapGetter.getString(map, "MsgT_tWork"))){
					    		continue;
					    	}else{
						    	Altitude += ","+ExceptionDataProcess.UnityDataProcess(MapGetter.getString(map, "MsgT_Altitude"),2);
								GPSMile += ","+ExceptionDataProcess.UnityDataProcess(MapGetter.getString(map, "MsgT_Imileage"),2);
								WorkTime += ","+ExceptionDataProcess.UnityDataProcess(MapGetter.getString(map, "MsgT_tWork"),2);
								PstnTime += ","+MapGetter.getString(map, "MsgT_PstnTime");
								
								PreMile = MapGetter.getDouble(map, "MsgT_Altitude");
								PrePstnTime = MapGetter.getString(map, "MsgT_PstnTime");
					    	}
					    }
					}
				}
				resultMap.put("VehicleID", VehicleID);
				resultMap.put("Altitude", Altitude);
				resultMap.put("GPSMile", GPSMile);
				resultMap.put("WorkTime", WorkTime);
				resultMap.put("PstnTime", PstnTime);
				dataMap.put(VehicleID, resultMap);
				Altitude = "";
				GPSMile = "";
				WorkTime = "";
				PstnTime = "";
				VehicleID = "";
				resultMap = new HashMap<String,Object>();;
				valList = null;
				isflag = true;
			}
			//处理总发动机操作时间、基于车轮的车辆速度、信息生成时间
			for(Map.Entry<String, List<Map<String, Object>>> entry : pgnListMap.entrySet()){
				valList = entry.getValue();
				VehicleID = entry.getKey();
				for(int i=0;i<valList.size();i++){
					map = valList.get(i);
					if(!StringUtil.isValid(MapGetter.getString(map, "egntotalhours")) || !StringUtil.isValid(MapGetter.getString(map, "msgp_msgtime")) || !StringUtil.isValid(MapGetter.getString(map, "speed"))){
						continue;
					}
					if(Double.parseDouble(MapGetter.getString(map, "speed"))<1){
						continue;
					}
					if(isflag){
							EgnWorkTime = ExceptionDataProcess.UnityDataProcess(MapGetter.getString(map, "egntotalhours"),2);
							MsgTime = MapGetter.getString(map, "msgp_msgtime");
							Speed = ExceptionDataProcess.UnityDataProcess(MapGetter.getString(map, "speed"),2);
							isflag = false;
					}else{
						EgnWorkTime += ","+ExceptionDataProcess.UnityDataProcess(MapGetter.getString(map, "egntotalhours"),2);
						MsgTime += ","+MapGetter.getString(map, "msgp_msgtime");
						Speed += ","+ExceptionDataProcess.UnityDataProcess(MapGetter.getString(map, "speed"),2);
					}
				}
				//如果经过位置时间、海拔处理后某台设备id不符合要求进行处理
				if(null != dataMap.get(VehicleID) && dataMap.get(VehicleID).size()>0){
					dataMap.get(VehicleID).put("EgnWorkTime", EgnWorkTime);
					dataMap.get(VehicleID).put("MsgTime", MsgTime);
					dataMap.get(VehicleID).put("Speed", Speed);
				}else{
					Map<String,Object> pstnMap = new HashMap<String, Object>();
					pstnMap.put("VehicleID", VehicleID);
					pstnMap.put("Altitude", "");
					pstnMap.put("GPSMile", "");
					pstnMap.put("WorkTime", "");
					pstnMap.put("PstnTime", "");
					pstnMap.put("EgnWorkTime", EgnWorkTime);
					pstnMap.put("MsgTime", MsgTime);
					pstnMap.put("Speed", Speed);
					dataMap.put(VehicleID,pstnMap);
					pstnMap = null;
				}
				isflag = true;
			}
			//处理最终数据
			Map<String,Object> dateMap = new HashMap<String, Object>();
			for(Map.Entry<String, Map<String,Object>> entry : dataMap.entrySet()){
				dateMap =entry.getValue();
				resultList.add(dateMap);
			}
			this.insertVclRoadInfo(thisWorkDay, resultList, sqlList,isbakTable);
	}
	private void insertVclRoadInfo(String thisWorkDay,List<Map<String, Object>> resultList, List<String> sqlList,String isbakTable) {
		StringBuilder sql = new StringBuilder();
		Map<String,Object> mapRes = new HashMap<String, Object>();
		 MyConnectDSTransDAO mucdd=new MyConnectDSTransDAO();
		if(null != resultList && resultList.size() > 0){
			for(int i=0;i<resultList.size();i++){
				mapRes = resultList.get(i);
				sql.append("insert into Vcl_RoadInfo_"+thisWorkDay.replaceAll("-", ""));
				sql.append(" values('"+MapGetter.getString(mapRes, "VehicleID")+"','"+MapGetter.getString(mapRes, "Altitude")+"'");
				sql.append(",'"+MapGetter.getString(mapRes, "GPSMile")+"' ,'"+MapGetter.getString(mapRes, "WorkTime")+"'");
				sql.append(",'"+MapGetter.getString(mapRes, "PstnTime")+"'");
				sql.append(",'"+MapGetter.getString(mapRes, "EgnWorkTime")+"'");
				sql.append(" ,'"+MapGetter.getString(mapRes, "Speed")+"','"+MapGetter.getString(mapRes, "MsgTime")+"');");
				sqlList.add(sql.toString());
				sql = new StringBuilder();
			}
			logdata.info(sqlList.toString());//插入日志
			boolean flag=mucdd.batch(sqlList);
			//需要备份则将数据插入到备份数据库
			if(isbakTable.equals("1")){
				MyConnectDSTransDAO connect = new MyConnectDSTransDAO(true);
				boolean isbak = connect.batch(sqlList);
				if(!isbak){
					System.out.println("道路信息数据备份失败");
				}
			}
		}
	}
	private List<Map<String, Object>> getVclPgnRoadInfo(String thisWorkDay,String vclIDS2,Map<String,Object> param) {
		List<Map<String, Object>> list = null;
		StringBuilder sql = new StringBuilder();
		String linkDataBase="";
		//获取总发动机操作时间、基于车轮的车辆速度、信息生成时间
		if(null!=param){
			linkDataBase="openrowset('SQLOLEDB','"+param.get("dataBaseIp")+"';'"+param.get("user")+"';'"+param.get("password")+"',"+param.get("MsgPDataBase")+".dbo.Msg_PGN_"+thisWorkDay.replaceAll("-", "")+")";
			sql.append("SELECT msgp_vcl_id, MsgP_PGNValue9 as egntotalhours,MsgP_PGNValue4 as speed,msgp_msgtime FROM "+linkDataBase);
			sql.append(" where msgp_vcl_id = "+vclIDS2+" and MsgP_PGNValue9 IS NOT NULL AND MsgP_PGNValue4 IS NOT NULL order by MsgP_MsgTime ");
		}else{
			sql.append("SELECT msgp_vcl_id, MsgP_PGNValue9 as egntotalhours,MsgP_PGNValue4 as speed,msgp_msgtime FROM "+GlobalDBVar.getDBFullName_Conn("Msg_PGN_"+thisWorkDay.replaceAll("-", ""), "4", thisWorkDay+" 00:00:00"));
			sql.append(" where msgp_vcl_id = "+vclIDS2+" and MsgP_PGNValue9 IS NOT NULL AND MsgP_PGNValue4 IS NOT NULL order by MsgP_MsgTime ");
		}
		list = baseDAO.execQuery(sql.toString(), new Object[]{});
		
		return list;
	}
	private List<Map<String, Object>> getVclPstnRoadInfo(String thisWorkDay,String vclIDS2,Map<String,Object> param) {
		List<Map<String, Object>> list = null;
		StringBuilder sql = new StringBuilder();
		String linkDataBase="";
		if(null!=param){
			sql.append("select MsgT_Vcl_ID,MsgT_Altitude,MsgT_Imileage,MsgT_tWorkTime_UDS as MsgT_tWork,MsgT_PstnTime from ");
			//获取页面输入的数据库地址、用户名、密码、库名：openrowset('SQLOLEDB','192.168.88.252';'sa';'tykj66TYKJ',CTY_MS.dbo.V_VehicleInfo)
			linkDataBase="openrowset('SQLOLEDB','"+param.get("dataBaseIp")+"';'"+param.get("user")+"';'"+param.get("password")+"',"+param.get("MsgTDataBase")+".dbo.Msg_Timing_"+thisWorkDay.replaceAll("-", "")+")";
			sql.append(linkDataBase);
			sql.append("  where MsgT_Vcl_ID ="+vclIDS2+" and MsgT_EgnState=1 and MsgT_Imileage>0 order by MsgT_PstnTime asc");
		}else{
			sql.append("select MsgT_Vcl_ID,MsgT_Altitude,MsgT_Imileage,MsgT_tWorkTime_UDS as MsgT_tWork,MsgT_PstnTime from ");
			sql.append(GlobalDBVar.getDBFullName_Conn("Msg_Timing_"+thisWorkDay.replaceAll("-", ""), "4", thisWorkDay+" 00:00:00"));
			sql.append("  where MsgT_Vcl_ID = "+vclIDS2+" and MsgT_EgnState=1 and MsgT_Imileage>0 order by MsgT_PstnTime asc");
		}
		list = this.baseDAO.execQuery(sql.toString(), new Object[]{});
		return list;
	}
	
}
